import React, { useEffect, useRef, useState } from 'react'

// 传入属性：当前用户信息（头像，姓名，障碍等级）、退出登录事件处理函数
const VisuallyImpairedDashboard = ({ currentUser, onLogout }) => {
  const [isListening, setIsListening] = useState(false)
  const [transcript, setTranscript] = useState('')
  const [speechSupported, setSpeechSupported] = useState(false)
  const recognitionRef = useRef(null)

  const [videoCallActive, setVideoCallActive] = useState(false)
  const localVideoRef = useRef(null)
  const localStreamRef = useRef(null)

  const [obstacleActive, setObstacleActive] = useState(false)
  const cameraRef = useRef(null)
  const canvasRef = useRef(null)
  const detectionTimerRef = useRef(null)
  const lastVibrateRef = useRef(0)

  const [appointments, setAppointments] = useState([])
  const [appointmentForm, setAppointmentForm] = useState({ time: '', place: '', event: '' })

  const [helpRecords, setHelpRecords] = useState(() => {
    const key = `vi_help_records_${currentUser.id}`
    const saved = localStorage.getItem(key)
    if (saved) {
      try { return JSON.parse(saved) } catch {}
    }
    return []
  })

  // 检查浏览器是否支持语音识别
  useEffect(() => {
    const isSupported = 'webkitSpeechRecognition' in window || 'SpeechRecognition' in window
    setSpeechSupported(isSupported)
  }, [])

  // 初始化语音识别
  const initSpeechRecognition = () => {
    if (!speechSupported) {
      alert('您的浏览器不支持语音识别功能')
      return false
    }

    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    const recog = new SpeechRecognition()
    recog.continuous = true
    recog.interimResults = false
    recog.lang = 'zh-CN'

    recog.onstart = () => {
      setIsListening(true)
      console.log('语音识别已开始')
    }
    
    recog.onend = () => {
      setIsListening(false)
      console.log('语音识别已结束')
    }
    
    recog.onerror = (event) => {
      setIsListening(false)
      console.error('语音识别错误:', event.error)
      
      if (event.error === 'not-allowed') {
        alert('请允许浏览器使用麦克风权限')
      } else if (event.error === 'audio-capture') {
        alert('无法访问麦克风，请检查设备连接')
      }
    }
    
    recog.onresult = (event) => {
      const text = event.results[event.results.length - 1][0].transcript || ''
      setTranscript(text)
      console.log('识别结果:', text)
      
      const normalized = text.replace(/\s/g, '')
      if (normalized.includes('视频通话') || normalized.includes('视频')) {
        startVideoCall()
      } else if (normalized.includes('障碍物识别') || normalized.includes('障碍识别') || normalized.includes('障碍')) {
        startObstacleDetection()
      }
    }

    recognitionRef.current = recog
    return true
  }

  // 开始语音识别
  const startListening = () => {
    if (!recognitionRef.current) {
      if (!initSpeechRecognition()) return
    }
    
    try {
      recognitionRef.current.start()
    } catch (error) {
      console.error('启动语音识别失败:', error)
      alert('启动语音识别失败，请重试')
    }
  }

  // 停止语音识别
  const stopListening = () => {
    if (recognitionRef.current && isListening) {
      try {
        recognitionRef.current.stop()
      } catch (error) {
        console.error('停止语音识别失败:', error)
      }
    }
  }

  // 组件卸载时停止语音识别
  useEffect(() => {
    return () => {
      stopListening()
    }
  }, [])

  useEffect(() => {
    const key = `vi_help_records_${currentUser.id}`
    localStorage.setItem(key, JSON.stringify(helpRecords))
  }, [helpRecords, currentUser.id])

  const startVideoCall = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
      localStreamRef.current = stream
      if (localVideoRef.current) {
        localVideoRef.current.srcObject = stream
      }
      setVideoCallActive(true)
    } catch (e) {
      alert('无法打开摄像头/麦克风：' + (e.message || '请检查权限'))
    }
  }

  const stopVideoCall = () => {
    setVideoCallActive(false)
    if (localStreamRef.current) {
      localStreamRef.current.getTracks().forEach(t => t.stop())
      localStreamRef.current = null
    }
    if (localVideoRef.current) {
      localVideoRef.current.srcObject = null
    }
    // 可选：记录一次求助
    addHelpRecord({
      description: '视频通话',
      volunteer: '待分配',
      status: 'completed',
      duration: '—',
    })
  }

  const startObstacleDetection = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false })
      if (cameraRef.current) cameraRef.current.srcObject = stream
      setObstacleActive(true)

      // 简易检测：中心区域亮度与边缘变化，触发震动提醒
      const ctx = canvasRef.current.getContext('2d')
      const analyze = () => {
        if (!cameraRef.current || !obstacleActive) return
        const video = cameraRef.current
        const w = 320, h = 240
        canvasRef.current.width = w
        canvasRef.current.height = h
        ctx.drawImage(video, 0, 0, w, h)
        const cx = Math.floor(w * 0.3), cy = Math.floor(h * 0.3), cw = Math.floor(w * 0.4), ch = Math.floor(h * 0.4)
        const data = ctx.getImageData(cx, cy, cw, ch).data
        let sum = 0
        for (let i = 0; i < data.length; i += 4) {
          const r = data[i], g = data[i + 1], b = data[i + 2]
          const lum = 0.299 * r + 0.587 * g + 0.114 * b
          sum += lum
        }
        const avg = sum / (data.length / 4)
        const lowLight = avg < 60 // 过暗
        const now = Date.now()
        if (lowLight && now - lastVibrateRef.current > 1500) {
          if (navigator.vibrate) navigator.vibrate([200, 100, 200])
          lastVibrateRef.current = now
        }
      }
      detectionTimerRef.current = setInterval(analyze, 500)
    } catch (e) {
      alert('无法打开摄像头：' + (e.message || '请检查权限'))
    }
  }

  const stopObstacleDetection = () => {
    setObstacleActive(false)
    if (cameraRef.current && cameraRef.current.srcObject) {
      cameraRef.current.srcObject.getTracks().forEach(t => t.stop())
      cameraRef.current.srcObject = null
    }
    if (detectionTimerRef.current) {
      clearInterval(detectionTimerRef.current)
      detectionTimerRef.current = null
    }
  }

  const addHelpRecord = ({ description, volunteer, status = 'completed', duration = '—', rating }) => {
    const time = new Date().toISOString().slice(0, 16).replace('T', ' ')
    setHelpRecords(prev => [
      {
        id: Date.now(),
        description,
        volunteer,
        status,
        time,
        duration,
        rating: rating ?? 5.0,
      },
      ...prev,
    ])
  }

  const handleAppointmentChange = (e) => {
    const { name, value } = e.target
    setAppointmentForm(prev => ({ ...prev, [name]: value }))
  }

  const submitAppointment = (e) => {
    e.preventDefault()
    if (!appointmentForm.time || !appointmentForm.place || !appointmentForm.event) {
      alert('请完整填写预约时间、地点和事项')
      return
    }
    const newItem = { id: Date.now(), ...appointmentForm }
    setAppointments(prev => [newItem, ...prev])
    addHelpRecord({ description: `预约志愿者：${appointmentForm.event}（${appointmentForm.place}）`, volunteer: '待分配', status: 'pending', duration: '—' })
    setAppointmentForm({ time: '', place: '', event: '' })
    alert('预约已提交，我们将尽快为您匹配志愿者')
  }

  return (
    <div className="dashboard">
      <div className="user-header">
        <div className="user-avatar">{currentUser.avatar}</div>
        <div className="user-info">
          <h2>{currentUser.name}</h2>
          <p>视障人士 · 等级: {currentUser.disabilityLevel === 'low' ? '轻度' : currentUser.disabilityLevel === 'medium' ? '中度' : '重度'}</p>
          <p>已获得帮助: {helpRecords.length} 次</p>
        </div>
        <button className="btn btn-logout" onClick={onLogout}>
          退出登录
        </button>
      </div>

      <div className="dashboard-content">
        <div className="help-section">
          <h3>🎙️ 语音指令</h3>
          <div className="accessibility-info">
            <ul>
              <li>说"视频通话"打开实时视频通话</li>
              <li>说"障碍物识别"开启摄像头检测并震动提醒</li>
            </ul>
            <div style={{ marginTop: 12, display: 'flex', gap: 10, alignItems: 'center' }}>
              <button 
                className="btn btn-primary" 
                onClick={startListening}
                disabled={isListening}
                style={{ padding: '8px 16px', fontSize: '0.9rem' }}
              >
                {isListening ? '🎤 识别中...' : '🎤 开始语音识别'}
              </button>
              {isListening && (
                <button 
                  className="btn btn-secondary" 
                  onClick={stopListening}
                  style={{ padding: '8px 16px', fontSize: '0.9rem' }}
                >
                  ⏹️ 停止
                </button>
              )}
            </div>
            <p style={{ marginTop: 8, color: '#7f8c8d' }}>
              {speechSupported ? 
                (isListening ? `🎤 正在监听：${transcript || '等待语音...'}` : '🎤 点击按钮开始语音识别') : 
                '当前浏览器不支持语音识别'}
            </p>
          </div>
        </div>

        <div className="help-section">
          <h3>📞 实时视频通话</h3>
          {!videoCallActive ? (
            <button className="btn btn-primary" onClick={startVideoCall}>开始视频通话</button>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <video ref={localVideoRef} autoPlay playsInline muted style={{ width: '100%', borderRadius: 12, background: '#000' }} />
              <button className="btn btn-secondary" onClick={stopVideoCall}>结束通话</button>
              <div className="empty-state" style={{ marginTop: 8 }}>
                <div className="empty-icon">📡</div>
                <h4>演示模式</h4>
                <p>已打开本地摄像头。对接真实通话需后台信令与志愿者端。</p>
              </div>
            </div>
          )}
        </div>

        <div className="help-section">
          <h3>🚧 障碍物识别与震动提醒</h3>
          {!obstacleActive ? (
            <button className="btn btn-primary" onClick={startObstacleDetection}>开始识别</button>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <video ref={cameraRef} autoPlay playsInline muted style={{ width: '100%', borderRadius: 12, background: '#000' }} />
              <canvas ref={canvasRef} style={{ display: 'none' }} />
              <button className="btn btn-secondary" onClick={stopObstacleDetection}>停止识别</button>
              <div className="accessibility-info">
                <h3>提示</h3>
                <ul>
                  <li>中心区域过暗时会触发震动提醒（演示规则）</li>
                  <li>可在“通知设置”中关闭震动</li>
                </ul>
              </div>
            </div>
          )}
        </div>

        <div className="help-section">
          <h3>📅 预约志愿者</h3>
          <form className="form" onSubmit={submitAppointment}>
            <div className="input-group">
              <label htmlFor="appt-time">时间</label>
              <input id="appt-time" type="datetime-local" name="time" value={appointmentForm.time} onChange={handleAppointmentChange} required />
            </div>
            <div className="input-group">
              <label htmlFor="appt-place">地点</label>
              <input id="appt-place" type="text" name="place" placeholder="填写地点" value={appointmentForm.place} onChange={handleAppointmentChange} required />
            </div>
            <div className="input-group">
              <label htmlFor="appt-event">事项</label>
              <input id="appt-event" type="text" name="event" placeholder="说明您需要的帮助" value={appointmentForm.event} onChange={handleAppointmentChange} required />
            </div>
            <div className="button-group">
              <button type="submit" className="btn btn-primary">提交预约</button>
            </div>
          </form>
          {appointments.length > 0 && (
            <div className="service-history" style={{ marginTop: 16 }}>
              {appointments.map(a => (
                <div key={a.id} className="history-item">
                  <div className="history-header">
                    <strong>{a.event}</strong>
                    <span className="history-time">{a.time}</span>
                  </div>
                  <div className="history-details">
                    <span>📍 {a.place}</span>
                    <span>状态：待匹配志愿者</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="help-section">
          <h3>📱 我的求助记录</h3>
          {helpRecords.length === 0 ? (
            <div className="empty-state">
              <div className="empty-icon">📱</div>
              <h4>暂无求助记录</h4>
              <p>使用“视频通话”或“障碍物识别”，或提交预约后将生成记录。</p>
            </div>
          ) : (
            <div className="help-history">
              {helpRecords.map(r => (
                <div key={r.id} className="help-record">
                  <div className="record-header">
                    <span className={`record-status ${r.status === 'completed' ? 'completed' : 'pending'}`}>{r.status === 'completed' ? '已完成' : '进行中'}</span>
                    <span className="record-time">{r.time}</span>
                  </div>
                  <p className="record-description">{r.description}</p>
                  <div className="record-details">
                    <span>👨‍💼 志愿者: {r.volunteer}</span>
                    {r.rating != null && (<span>⭐ 评分: {r.rating}</span>)}
                    <span>⏱️ 用时: {r.duration}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default VisuallyImpairedDashboard
